/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */


let savefileto =
{
    onLoad: function()
    {
        Components.utils.import("resource://savefileto/savefileto.jsm", this);
        
        if (! this.savefileto.prefs.imageEnabled)
            return;
        
        // save single image
        this.mediaSaveAsButton1 = document.getElementById("imagesaveasbutton");
        this.saveFileToButton1 = this.createButton(this.mediaSaveAsButton1);
        this.deck1 = this.saveFileToButton1.parentNode;
        
        // save multiple images
        this.mediaSaveAsButton2 = document.getElementById("mediasaveasbutton");
        this.saveFileToButton2 = this.createButton(this.mediaSaveAsButton2);
        this.deck2 = this.saveFileToButton2.parentNode;
        
        let self = this;
        let commandCallback = function(e, folder) { e.stopPropagation(); self.onCommand(e, folder); };
        let options = {mainMenuPosition: "after_start"};
        let cascadeMenu = this.savefileto.createCascadeMenu(window, "image", commandCallback, options);
        cascadeMenu.attach(this.saveFileToButton1);
        cascadeMenu.attach(this.saveFileToButton2);
        
        let tree = document.getElementById("imagetree");
        tree.addEventListener("select", function() { self.onMediaTreeSelect(); }, false);
    },
    
    createButton: function(oldButton)
    {
        /**
         * <button (old) />
         *  =>
         * <deck>
         *   <hbox>
         *     <button (old) />
         *     <spacer flex="1" />
         *   </hbox>
         *   <button (new) />
         * </deck>
         */
        
        let newButton = oldButton.cloneNode(true);
        newButton.removeAttribute("id");
        newButton.setAttribute("type", "menu-button");
        newButton.setAttribute("class", "savefileto");
        
        let deck = document.createElement("deck");
        let oldButtonBox = document.createElement("hbox");
        let oldButtonBoxSpacer = document.createElement("spacer");
        oldButtonBoxSpacer.setAttribute("flex", 1);
        
        oldButton.parentNode.insertBefore(deck, oldButton);
        deck.appendChild(oldButtonBox);
        deck.appendChild(newButton);
        
        oldButtonBox.appendChild(oldButton);
        oldButtonBox.appendChild(oldButtonBoxSpacer);
        
        return newButton;
    },
    
    onMediaTreeSelect: function()
    {
        let tree = document.getElementById("imagetree");
        let rows = getSelectedRows(tree);
        let data = [gImageView.data[row] for each (row in rows)];
        let enabled = data.every(function(d) { return ((d[COL_IMAGE_NODE] instanceof HTMLImageElement) || d[COL_IMAGE_BG]); });
        
        this.deck1.selectedIndex = (enabled ? 1 : 0);
        this.deck2.selectedIndex = (enabled ? 1 : 0);
    },
    
    onCommand: function(e, folder)
    {
        let dir = folder.file;
        let prompt = (e.ctrlKey || this.savefileto.prefs.prompt);
        
        let tree = document.getElementById("imagetree");
        let rows = getSelectedRows(tree);
        let data = [gImageView.data[row] for each (row in rows)];
        let urls = [{imageUrl: d[COL_IMAGE_ADDRESS], docUri: makeURI(d[COL_IMAGE_NODE].baseURI)} for each (d in data)]
        
        let self = this;
        // post-save callback
        let saveCallback = function() { self.savefileto.addToRecent("image", folder, window); };
        
        if (urls.length == 1)
            this.saveImage(urls[0].imageUrl, urls[0].docUri, dir, prompt, saveCallback);
        else
            this.saveImages(urls, dir, prompt, saveCallback);
    },
    
    saveImages: function(urls, dir, prompt, saveCallback)
    {
        let self = this;
        // post-target-folder-has-been-selected callback
        let promptCallback = function(dir)
        {
            if (! dir)
                return;
            
            for each (let {imageUrl, docUri} in urls)
                self.saveImage(imageUrl, docUri, dir, false, null);
            
            if (saveCallback)
                saveCallback();
        }
        
        if (! prompt)
            promptCallback(dir);
        else
        {
            this.savefileto.preserveDownloadPrefs(null, this, function()
            {
                let prefs = {useDownloadDir: (! prompt), folderList: 2, dir: dir, lastDir: dir};
                this.savefileto.setDownloadPrefs({downloadPrefs: prefs});
                dir = selectSaveFolder(promptCallback);
            });
        }
    },
    
    saveImage: function(imageUrl, docUri, dir, prompt, saveCallback)
    {
        this.savefileto.preserveDownloadPrefs(docUri, this, function()
        {
            let prefs = {useDownloadDir: (! prompt), folderList: 2, dir: dir, lastDir: dir};
            let lastDownloadDir = {uri: docUri, file: dir};
            this.savefileto.setDownloadPrefs({downloadPrefs: prefs, lastDownloadDir: lastDownloadDir});
            
            // chrome://global/content/contentAreaUtils.js
            // saveImageURL(aURL, aFileName, aFilePickerTitleKey, aShouldBypassCache, aSkipPrompt, aReferrer, aDoc)
            saveImageURL(imageUrl, null, "SaveImageTitle", false, (! prompt), docUri, gDocument);
        });
        
        if (saveCallback)
            saveCallback();
    },
}


window.addEventListener("load", function() { savefileto.onLoad(); }, false);
